package code.c09;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author thinkpad - 83start
 * @version v1.0
 * @create 2022/11/1 14:27
 * @package code.e09
 * @description Lock锁
 */
class Window2 implements Runnable {
    private static int ticket = 100;

    // 步骤一：实例化 lock
    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                // 步骤二：调用lock
                lock.lock();
                if (ticket > 0) {

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + "：买票-- > 票号：" + ticket);
                    ticket--;
                }
            } finally {
                // 步骤三：调用解锁方法
                lock.unlock();
            }

        }
    }
}

public class Ex05 {
    public static void main(String[] args) {
        Window2 window2 = new Window2();

        Thread thread1 = new Thread(window2);
        Thread thread2 = new Thread(window2);
        Thread thread3 = new Thread(window2);

        thread1.setName("窗口1");
        thread2.setName("窗口2");
        thread3.setName("窗口3");

        thread1.start();
        thread2.start();
        thread3.start();
    }

}
